﻿//var sjn = $.noop;

//window.location.href：获取完整url的方法：,即scheme://host:port/path?query#fragment
//window.location.protocol：获取rul协议scheme
//window.location.host：获取host
//window.location.port：获取端口号
//window.location.pathname：获取url路径
//window.location.search：获取参数query部分，注意此处返回的是?query
//window.location.hash：获取锚点，#fragment



///sjn
///对url进行处理
//  kv              url后的参数用key/value的对象方式保存（url解码）
//  skv             url后的参数用key/value的对象方式保存（url未解码 
//  attr(key,value)     修改、获取kv中的值
//  removeAttr(key)     删除kv中的kev
//  tohref()        把kv转换为url
//  go()       地址跳转
myurl = function (url) {
    var jurl = {};
    var proc = function (href) {
        //返回对象。Jquery Json Url
        jurl.kv = {};               //decodeURIComponent(unescape)解码后的key、value  用encodeURIComponent（escape）编码
        jurl.skv = {};              //未解的原始key、value

        //修改以key/Values 方式存储  
        //只传key时 是取url中的参数值
        //key和value同时有值时，是增加url中的参数

        jurl.attr = function (key, value) {
            if ($.isPlainObject(key)) {
                jurl.kv = $.extend(jurl.kv, key);
                jurl.newHref = jurl.tohref();

                //                var queryJson = key;
                //                $(sjn.GetJsonKeys(queryJson)).each(function (i, d) {
                //                    jurl.attr(d, queryJson[d]);
                //                    jurl.newHref = jurl.tohref();
                //                });
                return jurl;
            }
            else if (typeof (value) != "undefined") {
                jurl.kv[key] = value;
                jurl.newHref = jurl.tohref();
                return jurl;
            }
            else return jurl.kv[key];
        }

        //删除url中的参数
        jurl.removeAttr = function (key) {
            delete jurl.kv[key];
            jurl.newHref = jurl.tohref();
            return jurl;
        }

        //返新的数组 转换为url
        jurl.tohref = function () {
            var queryAry = [];
            $(sjn.GetJsonKeys(this.kv)).each(function (i, d) {
                queryAry.push(encodeURIComponent(d) + "=" + encodeURIComponent(jurl.kv[d]));

            });
            return jurl.url + (queryAry.length > 0 ? "?" : "") + queryAry.join("&");
        }

        //url地址跳转
        jurl.go = function (url) {
            if (url) {
                location.href = url;
            } else {
                location.href = jurl.newHref;
            }
        }

        //获取url中所有参数 
        if (jurl.search != "") {
            var seg2 = jurl.search.slice(1);
            if (seg2) {
                var seg3 = seg2.split('&');
                $(seg3).each(function (i, d) {
                    var seg4 = d.split('='),

                    key = decodeURIComponent(seg4[0]),
                    value = decodeURIComponent(seg4[1]);
                    jurl.kv[key] = value;           //解码的key / value
                    jurl.skv[key] = seg4[1];        //未解码的key / value
                });
            }
        }
        return jurl;
    };

    //如果url有值时，处理url
    if (url) {
        jurl.href = url;
        jurl.newHref = url;
        jurl.host = window.location.protocol + "//" + window.location.host;
        if (url.indexOf("?") != -1) {
            jurl.search = url.substring(url.indexOf("?")); //获取参数query部分，注意此处返回的是?query     
            jurl.url = url.substring(0, url.indexOf("?"));
        } else {
            jurl.url = url.substring(0);
        }

        return proc(url.toString());
    }
    else {
        //没值时处理当前的url
        jurl.href = window.location.href;
        jurl.newHref = window.location.href;
        jurl.host = window.location.protocol + "//" + window.location.host;
        jurl.search = window.location.search;       //获取参数query部分，注意此处返回的是?query
        jurl.pathname = window.location.pathname;   //获取url路径
        jurl.hash = window.location.hash;           //获取锚点，#fragment
        jurl.url = jurl.host + jurl.pathname;
        return proc(window.location.href);
    };
};


//获取json对像的所有key值数组
GetJsonKeys = function (Dict) {
    var ret = [];
    for (var p in Dict) {
        ret.push(p);
    }
    return ret;
};



/*
//Summary：表单数据回添
//Remark：依赖库：jquery
*/
myform = function (d) {
    p = {
        map: {},   //data中元素名的映射
        data: null,     //表单中，元素名和值
        formid: "aspnetForm"    //表单ID或name
    };

    _init = function () {
        if ($.type(d) == "string") {
            d = $.parseJSON(d);
        }
        p = $.extend(p, d);
        $(GetJsonKeys(p.data)).each(function (i, item) {
            if (p.map[item] != undefined) {
                setForm(p.map[item], p.data[item]);
            } else {
                setForm(item, p.data[item]);
            }
        });
    }

    setForm = function (name, value) {
        var name, value, type, Obj, i, x;
        var FormObj = document.getElementById(p.formid) ? document.getElementById(p.formid) : null;
        Obj = (FormObj == null) ? document.getElementsByName(name) : eval('FormObj["' + name + '"]');
        if (Obj != undefined) {
            //判断表单项类型
            if (FormObj == null) {
                if (Number(Obj.length) == 0) return false;
                type = Obj[0].type;
            } else {
                if (Obj[0] != undefined) {
                    type = Obj[0].type;
                    if (type == undefined) { type = Obj.type; Obj = new Array(Obj); }
                } else {
                    type = Obj.type;
                    Obj = new Array(Obj);
                }
            }
            //向表单填值
            if (type == "radio") {
                for (i = 0; i < Obj.length; i++) {
                    if (Obj[i].value == (value.toString())) {
                        Obj[i].checked = true;
                    }
                }
            } else if (type == "checkbox") {
                value = "," + value + ",";
                for (i = 0; i < Obj.length; i++) {
                    if (value.indexOf("," + Obj[i].value + ",") > -1) {
                        Obj[i].checked = true;
                    }
                }
            } else if (type == 'select-multiple' || type == 'select-one') {
                if (value != null && value != undefined) {
                    value = value.toString().split(',');
                    for (i = 0; i < value.length; i++) {
                        for (x = 0; x < Obj[0].options.length; x++) {
                            if (Obj[0].options[x].value.toLowerCase() == value[i].replace(/^\s*(.*)\s*$/g, '$1').toLowerCase()) {
                                Obj[0].options[x].selected = true;
                            }
                        }
                    }
                }
            } else if (type == "textarea") {
                var frameId = "";
                for (i = 0; i < document.getElementsByTagName("iframe").length; i++) {
                    if (document.getElementsByTagName("iframe")[i].src.indexOf(name) >= 0) {
                        frameId = document.getElementsByTagName("iframe")[i].id;
                    }
                }
                if (frameId == "") {//普通Textarea
                    Obj[0].value = value;
                } else {//eWebEditor
                    eval(frameId + '.setHTML(value)');
                }
            } else {
                Obj[0].value = value;
            }
        }
    }

    _init();
}


//给领域加入数据
$.fn._setData = function (name, val) {
    var domain = $(this);
    var obj, type;
    if ($.isPlainObject(name)) {
        //obj = domain.find("[name='""']")

    } else {

    }

    var ceshi = function (n, v) {
        obj = domain.find("[name='" + n + "']");
        type = obj.attr("type");
        if (obj.is("select")) {

        }
        if (obj.is("textarea")) {

        }
        if (type == "") {

        }
    }

}





//获取容器中的所有控件的值key/value的方式返回对象
$.fn._getData = function () {
    var data = {};
    var o = $(this);
    var input = o.find("input");
    var select = o.find("select");
    var textarea = o.find("textarea");

    $.each(input, function (i, item) {
        item = $(item);
        var type = item.attr("type");
        var name = item.attr("name");
        var value = item.val() ? item.val() : null;

        if (type == "text" || type == "hidden" || type == "password") {
            if (value) {
                data[name] = value;
            }
        }

        if (type == "checkbox") {
            var cv = [];
            o.find("input[type='checkbox'][name='" + name + "']:checked")
            .each(function () {
                cv.push($(this).val());
            });
            if (cv.length > 0) {
                data[name] = cv.join(",");
            }
        }

        if (type == "radio") {
            value = o.find("input[type='radio'][name='" + name + "']:checked").val();
            data[name] = value;
        }
    });

    $.each(select, function (i, item) {
        item = $(item);
        var name = item.attr("name");
        var value = item.val();
        data[name] = value;
    });

    $.each(textarea, function (i, item) {
        item = $(item);
        var name = item.attr("name");
        var value = item.val();
        if (value) {
            data[name] = value;
        }
    });
    return data;
}
//end 获取容器中的所有控件的值key/value的方式返回对象



//js 闭包 实例
; (function ($) {
    var sjn = function () {
        return sjn.fn._init();
    };

    sjn.toDate = function(str)
    {
        if (str.indexOf("/Date(") > -1) {
            str = str.replace("/Date(","").replace(")/","");
        }
        if (parseInt(str)!="NaN") {
            return new Date(parseInt(str));
        }
    }

    window.sjn = sjn;
})(this.sjn);  


/**
* 扩展基础类
* 日期格式化
**/
Date.prototype.format = function(pat){
	var year = this.getFullYear();
	var month = this.getMonth() + 1;
	var day = this.getDate();
	var hour = this.getHours();
	var minute = this.getMinutes();
	var second = this.getSeconds();
	// 两位补齐
	month = month > 9 ? month : "0" + month;
	day = day > 9 ? day : "0" + day;
	hour = hour > 9 ? hour : "0" + hour;
	minute = minute > 9 ? minute : "0" + minute;
	second = second > 9 ? second : "0" + second;
	if(!pat){
		pat = "yyyy-MM-dd";
	}
	pat = pat.replace(/yyyy/g, year);
	pat = pat.replace(/MM/g, month);
	pat = pat.replace(/dd/g, day);
	pat = pat.replace(/HH/gi, hour);
	pat = pat.replace(/mm/g, minute);
	pat = pat.replace(/ss/g, second);
	return pat;
}

////创建命名空间
//sjn.namespace = function (_names) {
//    var parts = ns_string.split('.'),
//        parent = {},
//        i;
//    for (i = 0; i < parts.length; i += 1) {
//        // 如果属性不存在，就创建
//        if (typeof parent[parts[i]] === "undefined") {
//            parent[parts[i]] = {};
//        }
//        parent = parent[parts[i]];
//    }
//    return parent;
//}









